<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="设备编号" prop="innerCode">
        <el-input
          v-model="queryParams.innerCode"
          placeholder="请输入设备编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属点位" prop="nodeId">
        <el-select v-model="queryParams.nodeId" placeholder="请选择所属点位" clearable>
          <el-option
            v-for="node in nodeList"
            :key="node.id"
            :label="node.nodeName"
            :value="node.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商圈类型" prop="businessType">
        <el-select v-model="queryParams.businessType" placeholder="请选择商圈类型" clearable>
          <el-option
            v-for="dict in business_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属区域" prop="regionId">
        <el-select v-model="queryParams.regionId" placeholder="请选择所属区域" clearable>
          <el-option
            v-for="region in regionList"
            :key="region.id"
            :label="region.regionName"
            :value="region.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="合作商" prop="partnerId">
        <el-select v-model="queryParams.partnerId" placeholder="请选择合作商" clearable>
          <el-option
            v-for="partner in partnerList"
            :key="partner.id"
            :label="partner.partnerName"
            :value="partner.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="设备型号" prop="vmTypeId">
        <el-select v-model="queryParams.vmTypeId" placeholder="请选择设备型号" clearable>
          <el-option
            v-for="vmType in vmTypeList"
            :key="vmType.id"
            :label="vmType.name"
            :value="vmType.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="设备状态" prop="vmStatus">
        <el-select v-model="queryParams.vmStatus" placeholder="请选择设备状态，0:未投放;1-运营;3-撤机" clearable>
          <el-option
            v-for="dict in vm_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="策略" prop="policyId">
        <el-input
          v-model="queryParams.policyId"
          placeholder="请输入策略id"
          clearable
          @keyup.enter="handleQuery"
        />
        <!-- 注意：策略下拉框需要策略列表API支持，目前保持文本输入框 -->
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['manage:vm:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['manage:vm:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['manage:vm:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['manage:vm:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="vmList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="主键" align="center" prop="id" /> -->
      <el-table-column label="设备编号" align="center" prop="innerCode" />
      <el-table-column label="设备型号" align="center" prop="vmTypeId">
        <template #default="scope">
          {{ getVmTypeName(scope.row.vmTypeId) }}
        </template>
      </el-table-column>
      <el-table-column label="详细地址" align="left" prop="addr" :show-overflow-tooltip="true"/>
      <el-table-column label="合作商" align="center" prop="partnerId">
        <template #default="scope">
          {{ getPartnerName(scope.row.partnerId) }}
        </template>
      </el-table-column>
      <el-table-column label="设备状态" align="center" prop="vmStatus">
        <template #default="scope">
          <dict-tag :options="vm_status" :value="scope.row.vmStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="300">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleView(scope.row)" v-hasPermi="['manage:vm:edit']">货道</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdatePolicy(scope.row)" v-hasPermi="['manage:vm:edit']">策略</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['manage:vm:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['manage:vm:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="vmRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="设备编号" prop="innerCode" v-if="form.id == null">
          <!-- <el-input v-model="form.innerCode" placeholder="请输入设备编号" style="width: 100%" /> -->
          <template #default>
            <span>{{ form.id == null ? '系统自动生成' : form.innerCode }}</span>
          </template>
        </el-form-item>
        <el-form-item label="设备编号" v-if="form.id != null">
          {{ form.innerCode }}
        </el-form-item>
        <el-form-item label="供货时间" v-if="form.id != null">
          {{ formatDateTime(form.lastSupplyTime) }}
        </el-form-item>
        <el-form-item label="选择型号" v-if="form.id != null">
          {{ getVmTypeName(form.vmTypeId) }}
        </el-form-item>
        <el-form-item label="设备容量" v-if="form.id != null">
          {{ form.channelMaxCapacity }}
        </el-form-item>
        <el-form-item label="选择点位" prop="nodeId">
          <el-select v-model="form.nodeId" placeholder="请选择所属点位" clearable style="width: 100%">
            <el-option
              v-for="node in nodeList"
              :key="node.id"
              :label="node.nodeName"
              :value="node.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择型号" prop="vmTypeId" v-if="form.id == null">
          <el-select v-model="form.vmTypeId" placeholder="请选择设备型号" clearable style="width: 100%">
            <el-option
              v-for="vmType in vmTypeList"
              :key="vmType.id"
              :label="vmType.name"
              :value="vmType.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="合作商" v-if="form.id != null">
          {{ getPartnerName(form.partnerId) }}
        </el-form-item>
        <el-form-item label="所属区域" v-if="form.id != null">
          {{ getRegionName(form.regionId) }}
        </el-form-item>
        <el-form-item label="设备地址" v-if="form.id != null">
          {{ form.addr }}
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 货道管理弹窗 -->
    <el-dialog 
      title="货道管理" 
      v-model="channelDialogOpen" 
      width="80%" 
      append-to-body
      :close-on-click-modal="false"
    >
      <div class="channel-container">
        <div class="vm-info">
          <el-descriptions :column="3" border>
            <el-descriptions-item label="设备编号">{{ currentVmInfo.innerCode }}</el-descriptions-item>
            <el-descriptions-item label="设备型号">{{ vmTypeInfo.name }}</el-descriptions-item>
            <el-descriptions-item label="设备容量">{{ vmTypeInfo.channelMaxCapacity }}个</el-descriptions-item>
            <el-descriptions-item label="货道规格">{{ vmTypeInfo.vmRow }}行 × {{ vmTypeInfo.vmCol }}列</el-descriptions-item>
            <el-descriptions-item label="详细地址">{{ currentVmInfo.addr }}</el-descriptions-item>
            <el-descriptions-item label="设备状态">
              <dict-tag :options="vm_status" :value="currentVmInfo.vmStatus"/>
            </el-descriptions-item>
          </el-descriptions>
          <!-- 状态信息 -->
          <div style="margin-top: 10px; font-size: 12px; color: #666;" v-if="pendingChannelUpdates.size > 0">
            <span>待更新货道数量: {{ pendingChannelUpdates.size }}</span>
          </div>
        </div>
        
        <div class="channel-grid" v-if="vmTypeInfo.vmRow && vmTypeInfo.vmCol">
          <div class="grid-header">
            <span>货道布局 ({{ vmTypeInfo.vmRow }}行 × {{ vmTypeInfo.vmCol }}列)</span>
          </div>
          <div 
            class="channel-grid-container" 
            :style="{ 
              gridTemplateColumns: `repeat(${vmTypeInfo.vmCol}, 1fr)`,
              gridTemplateRows: `repeat(${vmTypeInfo.vmRow}, 1fr)`
            }"
          >
            <div 
              v-for="(channel, index) in getChannelGrid()" 
              :key="index"
              class="channel-item"
            >
              <div 
                class="channel-slot"
                :class="{
                  'has-product': channel && channel.skuId,
                  'empty': !channel || !channel.skuId
                }"
              >
                <div v-if="channel && channel.skuId" class="channel-content">
                  <div class="channel-number">{{ channel.channelCode }}</div>
                  <div class="product-image" v-if="getSkuInfo(channel)?.skuImage">
                    <image-preview :src="getSkuInfo(channel).skuImage" :width="40" :height="40"/>
                  </div>
                  <div class="product-name">{{ getSkuInfo(channel)?.skuName || '未知商品' }}</div>
                  <div class="brand-name" v-if="getSkuInfo(channel)?.brandName">
                    {{ getSkuInfo(channel).brandName }}
                  </div>
                  <div class="product-info">
                    <span class="price" v-if="getSkuInfo(channel)?.price">¥{{ (getSkuInfo(channel).price / 100).toFixed(2) }}</span>
                    <span class="stock">{{ channel.currentCapacity }}/{{ channel.maxCapacity }}</span>
                  </div>
                </div>
                <div v-else class="channel-empty">
                  <div class="channel-number">{{ getChannelCodeFromIndex(index) }}</div>
                  <div class="empty-text">空货道</div>
                </div>
              </div>
              <div class="channel-actions">
                <el-button 
                  v-if="channel && channel.skuId"
                  type="primary" 
                  size="small" 
                  disabled
                  class="action-btn"
                >
                  添加
                </el-button>
                <el-button 
                  v-if="channel && channel.skuId"
                  type="danger" 
                  size="small" 
                  @click="handleDeleteChannel(channel)"
                  class="action-btn"
                >
                  删除
                </el-button>
                <el-button 
                  v-if="!channel || !channel.skuId"
                  type="primary" 
                  size="small" 
                  @click="handleAddChannel(getChannelCodeFromIndex(index))"
                  class="action-btn"
                >
                  添加
                </el-button>
                <el-button 
                  v-if="!channel || !channel.skuId"
                  type="danger" 
                  size="small" 
                  disabled
                  class="action-btn"
                >
                  删除
                </el-button>
              </div>
            </div>
          </div>
        </div>
        
        <div v-else class="no-channel-info">
          <el-empty description="暂无货道信息" />
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleChannelDialogClose">关 闭</el-button>
          <el-button type="primary" @click="handleConfirmChannelUpdates" v-if="pendingChannelUpdates.size > 0">确认更新</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 商品选择弹窗 -->
    <el-dialog 
      title="选择商品" 
      v-model="skuDialogOpen" 
      width="70%" 
      append-to-body
      :close-on-click-modal="false"
    >
      <div class="sku-selection-container">
        <!-- 搜索区域 -->
        <div class="search-section">
          <el-form :model="skuSearchParams" :inline="true">
            <el-form-item label="商品名称">
              <el-input
                v-model="skuSearchParams.skuName"
                placeholder="请输入商品名称"
                clearable
                @keyup.enter="handleSkuSearch"
                style="width: 200px"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleSkuSearch">搜索</el-button>
              <el-button icon="Refresh" @click="handleSkuSearchReset">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 商品列表 -->
        <div class="sku-list">
          <el-table 
            :data="skuList" 
            v-loading="loading"
            @row-click="handleSkuRowClick"
            highlight-current-row
            style="width: 100%"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="商品图片" align="center" width="80">
              <template #default="scope">
                <image-preview 
                  v-if="scope.row.skuImage" 
                  :src="scope.row.skuImage" 
                  :width="40" 
                  :height="40"
                />
                <span v-else>无图片</span>
              </template>
            </el-table-column>
            <el-table-column label="商品名称" prop="skuName" show-overflow-tooltip />
            <el-table-column label="品牌名称" prop="brandName" show-overflow-tooltip />
            <el-table-column label="规格" prop="unit" width="100" />
            <el-table-column label="价格" width="100">
              <template #default="scope">
                ¥{{ (scope.row.price / 100).toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" align="center">
              <template #default="scope">
                <el-button 
                  type="primary" 
                  size="small" 
                  @click="handleSelectSku(scope.row)"
                >
                  选择
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="skuDialogOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 策略弹窗 -->
    <el-dialog 
      title="更改策略" 
      v-model="policyDialogOpen" 
      width="500px" 
      append-to-body
    >
    <el-form ref="vmRef" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="策略" prop="policyId">
        <el-select v-model="form.policyId" placeholder="请选择策略" clearable style="width: 100%">
          <el-option
            v-for="policy in policyList"
            :key="policy.policyId"
            :label="policy.policyName"
            :value="policy.policyId"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitPolicyForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Vm">
import { listVm, getVm, delVm, addVm, updateVm } from "@/api/manage/vm";
import { listNode } from "@/api/manage/node";
import { listRegion } from "@/api/manage/region";
import { listPartner } from "@/api/manage/partner";
import { listVmType } from "@/api/manage/vmType";
import { listChannel, listChannelByInnerCode, updateChannel, addChannel, batchUpdateChannelConfig } from "@/api/manage/channel";
import { listSku } from "@/api/manage/sku";
import { loadAllParams } from "@/api/page";
import { listPolicy } from "@/api/manage/policy";

const { proxy } = getCurrentInstance();
const { vm_status, business_type } = proxy.useDict('vm_status', 'business_type');

const vmList = ref([]);
const nodeList = ref([]);
const regionList = ref([]);
const partnerList = ref([]);
const vmTypeList = ref([]);
const policyList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

// 货道弹窗相关状态
const channelDialogOpen = ref(false);
const channelList = ref([]);
const currentVmInfo = ref({});
const vmTypeInfo = ref({});
// 策略弹窗相关状态
const policyDialogOpen = ref(false);
// 商品选择弹窗相关状态
const skuDialogOpen = ref(false);
const skuList = ref([]);
const skuSearchParams = ref({
  skuName: '',
  pageNum: 1,
  pageSize: 100
});
const selectedSku = ref(null);
const currentChannelCode = ref('');
const pendingChannelUpdates = ref(new Map()); // 存储待更新的货道数据

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    innerCode: null,
    nodeId: null,
    businessType: null,
    regionId: null,
    partnerId: null,
    vmTypeId: null,
    vmStatus: null,
    runningStatus: null,
    policyId: null,
  },
  rules: {
    nodeId: [
      { required: true, message: "点位Id不能为空", trigger: "blur" }
    ],
    vmTypeId: [
      { required: true, message: "设备型号不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询设备管理列表 */
function getList() {
  loading.value = true;
  listVm(queryParams.value).then(response => {
    vmList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 查询点位列表 */
function getNodeList() {
  listNode(loadAllParams).then(response => {
    nodeList.value = response.rows || [];
  });
}

/** 查询区域列表 */
function getRegionList() {
  listRegion(loadAllParams).then(response => {
    regionList.value = response.rows || [];
  });
}

/** 查询合作商列表 */
function getPartnerList() {
  listPartner(loadAllParams).then(response => {
    partnerList.value = response.rows || [];
  });
}

/** 查询设备型号列表 */
function getVmTypeList() {
  listVmType(loadAllParams).then(response => {
    vmTypeList.value = response.rows || [];
  });
}

/** 查询策略列表 */
function getPolicyList() {
  listPolicy(loadAllParams).then(response => {
    policyList.value = response.rows || [];
  });
}

/** 根据ID获取设备型号名称 */
function getVmTypeName(id) {
  if (!id) return '-';
  const vmType = vmTypeList.value.find(item => item.id === id);
  return vmType ? vmType.name : id;
}

/** 根据ID获取合作商名称 */
function getPartnerName(id) {
  if (!id) return '-';
  const partner = partnerList.value.find(item => item.id === id);
  return partner ? partner.partnerName : id;
}

/** 根据ID获取区域名称 */
function getRegionName(id) {
  if (!id) return '-';
  const region = regionList.value.find(item => item.id === id);
  return region ? region.regionName : id;
}

/** 根据ID获取点位名称 */
function getNodeName(id) {
  if (!id) return '-';
  const node = nodeList.value.find(item => item.id === id);
  return node ? node.nodeName : id;
}

/** 根据ID获取策略名称 */
function getPolicyName(id) {
  if (!id) return '-';
  const policy = policyList.value.find(item => item.id === id);
  return policy ? policy.policyName : id;
}


/** 格式化日期时间 */
function formatDateTime(dateTime) {
  if (!dateTime) return '-';
  const date = new Date(dateTime);
  if (isNaN(date.getTime())) return dateTime;
  
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 取消按钮
function cancel() {
  open.value = false;
  policyDialogOpen.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    innerCode: null,
    channelMaxCapacity: null,
    nodeId: null,
    addr: null,
    lastSupplyTime: null,
    businessType: null,
    regionId: null,
    partnerId: null,
    vmTypeId: null,
    vmStatus: null,
    runningStatus: null,
    longitudes: null,
    latitude: null,
    clientId: null,
    policyId: null,
    createTime: null,
    updateTime: null
  };
  proxy.resetForm("vmRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加设备管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getVm(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改设备管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["vmRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateVm(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addVm(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 提交策略按钮 */
function submitPolicyForm() {
  proxy.$refs["vmRef"].validate(valid => {
    if (valid) {
      updateVm(form.value).then(response => {
        proxy.$modal.msgSuccess("修改成功");
        policyDialogOpen.value = false;
        getList();
      });
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除设备管理编号为"' + _ids + '"的数据项？').then(function() {
    return delVm(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/vm/export', {
    ...queryParams.value
  }, `vm_${new Date().getTime()}.xlsx`)
}

/** 查看货道按钮操作 */
function handleView(row) {
  currentVmInfo.value = { ...row };
  
  // 根据vmTypeId获取设备型号信息
  const vmType = vmTypeList.value.find(item => item.id === row.vmTypeId);
  if (vmType) {
    vmTypeInfo.value = { ...vmType };
  } else {
    proxy.$modal.msgError("未找到设备型号信息");
    return;
  }
  
  // 查询该设备的货道信息
  loadChannelData(row.innerCode);
}

/* 更改策略按钮操作 */
function handleUpdatePolicy(row) {
  reset();
  policyDialogOpen.value = true;
  title.value = "更改策略";

  const _id = row.id || ids.value
  // 设置设备id和点位id
  form.value.nodeId = row.nodeId;
  form.value.id = _id;
  // 设置设备策略id
  form.value.policyId = row.policyId;
}

/** 加载货道数据 */
async function loadChannelData(innerCode) {
  try {
    // 使用新的API获取包含商品信息的货道数据
    const response = await listChannelByInnerCode(innerCode);
    channelList.value = response.data || [];
    
    // 货道数据已包含完整的商品信息，无需额外API调用
    
    channelDialogOpen.value = true;
  } catch (error) {
    proxy.$modal.msgError("查询货道信息失败");
    console.error("查询货道信息失败:", error);
  }
}

/** 获取货道网格数据 */
function getChannelGrid() {
  if (!vmTypeInfo.value.vmRow || !vmTypeInfo.value.vmCol) {
    return [];
  }
  
  const totalSlots = vmTypeInfo.value.vmRow * vmTypeInfo.value.vmCol;
  const grid = new Array(totalSlots).fill(null);
  
  // 将货道数据填充到对应的网格位置
  channelList.value.forEach(channel => {
    if (channel && channel.channelCode) {
      // 从channelCode解析行列位置，格式如 "1-1", "2-3" 等
      const parts = channel.channelCode.split('-');
      if (parts.length >= 2) {
        const row = parseInt(parts[0]) - 1; // 行号从0开始
        const col = parseInt(parts[1]) - 1; // 列号从0开始
        const index = row * vmTypeInfo.value.vmCol + col;
        
        if (index >= 0 && index < totalSlots) {
          grid[index] = channel;
        }
      }
    }
  });
  
  return grid;
}

/** 获取货道编号 */
function getChannelNumber(index) {
  return index + 1;
}

/** 从channelCode中提取货道编号 */
function getChannelNumberFromCode(channelCode) {
  if (!channelCode) return '';
  // channelCode格式如 "1-1", "2-3" 等，提取后面的数字作为货道编号
  const parts = channelCode.split('-');
  return parts[1] || parts[0] || '';
}

/** 根据网格索引计算channelCode格式 */
function getChannelCodeFromIndex(index) {
  if (!vmTypeInfo.value.vmRow || !vmTypeInfo.value.vmCol) {
    return index + 1;
  }
  
  const row = Math.floor(index / vmTypeInfo.value.vmCol) + 1;
  const col = (index % vmTypeInfo.value.vmCol) + 1;
  return `${row}-${col}`;
}

/** 获取商品信息（直接从channel.sku获取） */
function getSkuInfo(channel) {
  return channel?.sku || null;
}

/** 处理添加货道商品 */
function handleAddChannel(channelCode) {
  currentChannelCode.value = channelCode;
  loadSkuList();
  skuDialogOpen.value = true;
}

/** 处理删除货道商品 */
function handleDeleteChannel(channel) {
  proxy.$modal.confirm(`是否确认删除货道 ${channel.channelCode} 的商品？`).then(() => {
    // 本地更新：将skuId设置为0
    const updatedChannel = { ...channel, skuId: 0, sku: null };
    pendingChannelUpdates.value.set(channel.channelCode, updatedChannel);
    
    // 更新本地显示
    const channelIndex = channelList.value.findIndex(c => c.channelCode === channel.channelCode);
    if (channelIndex !== -1) {
      channelList.value[channelIndex] = updatedChannel;
    }
    
    proxy.$modal.msgSuccess(`货道 ${channel.channelCode} 的商品已标记删除，请点击确认更新保存到后端`);
  }).catch(() => {
    // 用户取消删除
  });
}

/** 加载商品列表 */
async function loadSkuList() {
  try {
    loading.value = true;
    const response = await listSku(skuSearchParams.value);
    skuList.value = response.rows || [];
  } catch (error) {
    proxy.$modal.msgError("查询商品列表失败");
    console.error("查询商品列表失败:", error);
  } finally {
    loading.value = false;
  }
}

/** 商品搜索 */
function handleSkuSearch() {
  skuSearchParams.value.pageNum = 1;
  loadSkuList();
}

/** 重置商品搜索 */
function handleSkuSearchReset() {
  skuSearchParams.value.skuName = '';
  skuSearchParams.value.pageNum = 1;
  loadSkuList();
}

/** 商品行点击 */
function handleSkuRowClick(row) {
  selectedSku.value = row;
}

/** 选择商品 */
function handleSelectSku(sku) {
  selectedSku.value = sku;
  
  // 查找现有货道数据
  const existingChannel = channelList.value.find(c => c.channelCode === currentChannelCode.value);
  
  // 创建更新后的货道数据
  const updatedChannel = {
    // 保留原有的其他字段
    ...existingChannel,
    // 更新关键字段
    channelCode: currentChannelCode.value,
    skuId: sku.skuId,
    sku: sku,
    // 如果是新货道，需要设置基本字段
    id: existingChannel?.id || null,
    vmId: existingChannel?.vmId || currentVmInfo.value.id,
    innerCode: existingChannel?.innerCode || currentVmInfo.value.innerCode,
    maxCapacity: existingChannel?.maxCapacity || 10, // 默认容量
    currentCapacity: existingChannel?.currentCapacity || 0, // 默认当前容量为0
    lastSupplyTime: existingChannel?.lastSupplyTime || null
  };
  
  // 存储到待更新列表
  pendingChannelUpdates.value.set(currentChannelCode.value, updatedChannel);
  
  // 更新本地显示
  const channelIndex = channelList.value.findIndex(c => c.channelCode === currentChannelCode.value);
  if (channelIndex !== -1) {
    channelList.value[channelIndex] = updatedChannel;
  } else {
    // 如果是新添加的货道，添加到列表中
    channelList.value.push(updatedChannel);
  }
  
  // 强制触发响应式更新
  channelList.value = [...channelList.value];
  
  proxy.$modal.msgSuccess(`已选择商品：${sku.skuName}，请点击确认更新保存到后端`);
  skuDialogOpen.value = false;
}

/** 验证货道数据 */
function validateChannelData(channelData) {
  const errors = [];
  
  if (!channelData.channelCode) {
    errors.push('货道编号不能为空');
  }
  
  if (channelData.skuId === undefined || channelData.skuId === null) {
    errors.push('商品ID不能为空');
  }
  
  if (!channelData.innerCode) {
    errors.push('设备编号不能为空');
  }
  
  return errors;
}

/** 确认更新货道数据到后端 */
async function handleConfirmChannelUpdates() {
  if (pendingChannelUpdates.value.size === 0) {
    proxy.$modal.msgInfo("没有待更新的货道数据");
    return;
  }
  
  try {
    loading.value = true;
    
    // 验证所有数据
    for (const [channelCode, channelData] of pendingChannelUpdates.value) {
      const validationErrors = validateChannelData(channelData);
      if (validationErrors.length > 0) {
        proxy.$modal.msgError(`货道 ${channelCode} 数据验证失败: ${validationErrors.join(', ')}`);
        return;
      }
    }
    
    // 构建批量更新数据
    const channelList = [];
    for (const [channelCode, channelData] of pendingChannelUpdates.value) {
      channelList.push({
        innerCode: channelData.innerCode,
        channelCode: channelData.channelCode,
        skuId: channelData.skuId
      });
    }
    
    const batchUpdateData = {
      innerCode: currentVmInfo.value.innerCode,
      channelList: channelList
    };
    
    // 使用批量更新API
    await batchUpdateChannelConfig(batchUpdateData);
    
    proxy.$modal.msgSuccess(`成功更新 ${pendingChannelUpdates.value.size} 个货道的数据`);
    pendingChannelUpdates.value.clear();
    
    // 重新加载货道数据以确保数据一致性
    await loadChannelData(currentVmInfo.value.innerCode);
    
  } catch (error) {
    proxy.$modal.msgError("更新货道数据失败");
    console.error("更新货道数据失败:", error);
  } finally {
    loading.value = false;
  }
}

/** 关闭货道弹窗 */
function handleChannelDialogClose() {
  if (pendingChannelUpdates.value.size > 0) {
    proxy.$modal.confirm('有未保存的货道更改，确定要关闭吗？关闭后更改将丢失。').then(() => {
      pendingChannelUpdates.value.clear();
      channelDialogOpen.value = false;
    }).catch(() => {
      // 用户取消关闭
    });
  } else {
    channelDialogOpen.value = false;
  }
}


getPolicyList();
getList();
getNodeList();
getRegionList();
getPartnerList();
getVmTypeList();
</script>

<style scoped>
.channel-container {
  padding: 20px;
}

.vm-info {
  margin-bottom: 20px;
}

.channel-grid {
  margin-top: 20px;
}

.grid-header {
  margin-bottom: 15px;
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.channel-grid-container {
  display: grid;
  gap: 10px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.channel-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.channel-slot {
  min-height: 140px;
  border: 2px solid #dcdfe6;
  border-radius: 6px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #ffffff;
  transition: all 0.3s ease;
  position: relative;
  padding: 8px;
}

.channel-slot:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}

.channel-slot.has-product {
  border-color: #67c23a;
  background-color: #f0f9ff;
}

.channel-slot.empty {
  border-color: #e4e7ed;
  background-color: #fafafa;
}

.channel-content {
  text-align: center;
  padding: 5px;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.channel-empty {
  text-align: center;
  padding: 10px;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.channel-actions {
  display: flex;
  gap: 4px;
  width: 100%;
  justify-content: center;
}

.action-btn {
  flex: 1;
  font-size: 10px;
  padding: 4px 8px;
  min-width: 0;
}

.channel-number {
  font-size: 14px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 8px;
}

.product-image {
  margin: 2px 0;
}

.product-image img {
  border-radius: 4px;
  object-fit: cover;
}

.product-name {
  font-size: 11px;
  color: #303133;
  word-break: break-all;
  line-height: 1.3;
  max-height: 2.6em;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
}

.brand-name {
  font-size: 10px;
  color: #909399;
  font-weight: 500;
  margin: 2px 0;
}

.product-info {
  display: flex;
  justify-content: space-between;
  font-size: 11px;
}

.price {
  color: #e6a23c;
  font-weight: bold;
}

.stock {
  color: #67c23a;
}

.empty-text {
  font-size: 12px;
  color: #909399;
}

.no-channel-info {
  text-align: center;
  padding: 40px;
}

/* 商品选择弹窗样式 */
.sku-selection-container {
  padding: 20px;
}

.search-section {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 6px;
}

.sku-list {
  max-height: 400px;
  overflow-y: auto;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .channel-grid-container {
    gap: 8px;
    padding: 15px;
  }
  
  .channel-item {
    gap: 6px;
  }
  
  .channel-slot {
    min-height: 120px;
  }
  
  .product-image img {
    width: 30px !important;
    height: 30px !important;
  }
  
  .product-name {
    font-size: 10px;
  }
  
  .brand-name {
    font-size: 9px;
  }
  
  .product-info {
    font-size: 9px;
  }
  
  .action-btn {
    font-size: 9px;
    padding: 2px 4px;
  }
  
  .sku-selection-container {
    padding: 10px;
  }
  
  .search-section {
    padding: 10px;
  }
}
</style>
